-- UIWorkshopGuide
-- Create by zouyb
-- 新手指引界面

require "game/ui/form/workshop/UINewWorkshop"

--UIWorkshopGuide继承自Layer
UIWorkshopGuide = class("UIWorkshopGuide", function()
    return cc.Layer:create();
end);

function UIWorkshopGuide.create(itemId)
    return UIWorkshopGuide.new(itemId);
end

local resize;

-- 混合颜色，灰色
local blendColor = TextStyleM.TEXT_COLOR_BLEND;
-- 混合颜色，白色
local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

-- 每次生产几个金币
local produceCountEachTime = 1;
-- 生产的总金币数
local totalProduceCount = 0;

--构造函数
function UIWorkshopGuide:ctor(itemId)
    self:setName("UIWorkshopGuide");
    self.itemId = itemId;

    --初始化
    local node = cc.CSLoader:createNode("layout/workshop/WorkshopGuide.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.slimeAnimNode = findChildByName(self.node, "layer/slime_anim");

    resize(self);

    -- 组件列表
    self.elements = {};
    local bg = findChildByName(self.node, "bg");
    self.elements[bg:getName()] = bg;

    local layer = findChildByName(self.node, "layer");
    local children = layer:getChildren();
    local len = table.getn(children);
    for i = 1, len do
        local child = children[i];
		if child:getName() ~= "mask" then
			self.elements[child:getName()] = child;
		end
    end

    -- 金币变动的回调处理
    ME.user.dbase:registerCb("UIWorkshopGuide", { "money", }, function()
        self:updateMoney();
    end);

    self:updateMoney();

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            if UIMgr.getCurrentScene().mainMap then
                UIMgr.getCurrentScene().mainMap:show();
            end
            ME.user.dbase:removeCb("UIWorkshopGuide", { "money", });
        elseif ev == "enter" then
            if UIMgr.getCurrentScene().mainMap then
                UIMgr.getCurrentScene().mainMap:hide();
            end

            if UIMgr.getCurrentScene().topMenu then
                UIMgr.getCurrentScene().topMenu:setVisible(false);
            end
        end
    end);

    -- 开始播放效果
    self:playEffect();
end

resize = function(self)
    local node = self.node;

    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local scale;
    if h / w > 1.5 then
        scale = h / 1136;
    else
        scale = w / 768;
    end

    local bg = findChildByName(self.node, "bg");
    bg:setScale(scale);
    bg:setPosition(w / 2, 0);

    local mask = findChildByName(self.node, "mask");
    mask:setScale(scale);
    mask:setPosition(w / 2, 0);

    local layer = findChildByName(self.node, "layer");
    layer:setScale(scale);
    layer:setPosition(w / 2, 0);

    local prologue = findChildByName(self.node, "prologue_mask");
    prologue:setPosition(w / 2, 0);
    prologue:setContentSize(w, h);

    AlignM.alignToCenter(node, "CT");
    AlignM.alignToTopCenter(node, "TOP");
end

-- 刷新金币数量
function UIWorkshopGuide:updateMoney()
    local curMoney = ME.user.dbase:query("money", 0);

    local moneyLabel = findChildByName(self.node, "TOP/money_bar/value");
    moneyLabel:setString(tostring(curMoney));
end

-- 动画效果
function UIWorkshopGuide:playEffect()
	local step0;
    local step1;
    local step2;
    local step3;
    local step4;
    local step5;
    local step6;

	local mask = findChildByName(self.node, "mask");

	-- 0. 显示开场漫画
	step0 = function()
		mask:setVisible(true);
		playCartoonEffect(3, step1);
	end

    -- 1. 画面未激活，比较灰暗
    step1 = function()
		mask:setVisible(false);
        self:turnDark(true, {"slime_anim", "repair_anim"});
        step2();
    end

    -- 2. 显示序章
    step2 = function()
        self:showPrologue(step3);
    end

	-- 3. 冈布奥跳进来
    step3 = function()
        self:slimeJumpIn(step4);
    end

    -- 4. 拾取物品
    step4 = function()
        self:pickUpItems(step5);
    end

    -- 5. 修理炼金炉
    step5 = function()
        self:repairWorkshop(step6);
    end

    -- 6. 炼金炉开始工作
    step6 = function()
        self:startWorking();
    end

    step0();
end

-- 变暗
function UIWorkshopGuide:turnDark(flag, exceptList)
    local setColor = iif(flag, blendColor, normalColor);
    local unsetColor = iif(flag, normalColor, blendColor);

    local function isInExceptList(name)
        for _, tempName in pairs(exceptList) do
            if tempName == name then
                return true;
            end
        end

        return false;
    end

    for name, child in pairs(self.elements) do
        if not isInExceptList(name) then
            child:setColor(setColor);
        else
            child:setColor(unsetColor);
        end
    end
end

-- 旋转显示效果
function UIWorkshopGuide:rotateTextEffect(textNode, fontSize)
    local str = textNode:getString();
    local fontSize = fontSize * getLocFontSizeMulti();
    local bgPath = "images/ui/text_mask/text_mask2.png";

    genArtWordAndRotate(textNode, fontSize, bgPath);
end

-- 显示开场白
function UIWorkshopGuide:showPrologue( callback )
    local prologueParentNode = findChildByName(self.node, "prologue_mask");
    local CT = findChildByName(self.node, "CT");
    prologueParentNode:setVisible(true);

    local totalDelay = 0;

    local duration = 0.08;
    if getLang() ~= "zh" and getLang() ~= "tw" then
        duration = 0.03;
    end

    local effectNodes = {};
    for index = 1, 2 do
        local prologueNode = findChildByName(self.node, "CT/text"..index);
        local str = getLocStr("prologue_"..index);
        prologueNode:setString(str);
        prologueNode:setVisible(false);

        local fontSize = 40 * getLocFontSizeMulti() + (2 - index)*10;

        local callFunc = cc.CallFunc:create(function()
            prologueNode:setVisible(true);
            self:rotateTextEffect(prologueNode, fontSize);
        end);

        local delay = 0.01 + (index - 1) * 1;
        prologueNode:runAction(cc.Sequence:create(cc.DelayTime:create(delay), callFunc));

        totalDelay = totalDelay + delay
    end

    local function done()
        if CT:isVisible() then
            prologueParentNode:setVisible(false);
            CT:setVisible(false);
            callback();
        end
    end

    local function audim()
        AudioM.playFx("prologue");
    end

    performWithDelay(self, done, totalDelay + 3);
    performWithDelay(self, audim, 0);
end

-- 冈布奥跳进来
function UIWorkshopGuide:slimeJumpIn( callback )
    playEffect(self.slimeAnimNode, 1169, 0, 0);

    local function audim()
        AudioM.playFx("workshop_guide08");
    end

    performWithDelay(self, function() AudioM.playFx("workshop_guide01"); end, 0.25);
    performWithDelay(self, function() AudioM.playFx("workshop_guide06"); end, 6.3);
    performWithDelay(self, audim, 13.0);
    local function done()
        -- 待机动画
        self.slimeAnimNode:removeAllChildren();
        playEffect(self.slimeAnimNode, 1170, 0, 0);
        if callback then
            callback();
        end
    end
    performWithDelay(self.slimeAnimNode, done, 16.5);
end

-- 拾取物品
function UIWorkshopGuide:pickUpItems(callback)
    local function showItem(index)
        if index > 3 then
            if callback then
                callback();
            end
            return;
        end

        -- 物品变亮
        AudioM.playFx("workshop_itemappear");
        local item = self.elements["item"..index];
        item:setColor(normalColor);

        local function pickUpItem(index)
            -- 冈布奥跳过来
            self.slimeAnimNode:removeAllChildren();
            playEffect(self.slimeAnimNode, 1163, 0, 0);
            AudioM.playFx("workshop_guide0" .. (index + 1));

            local pos;
            if item:getPositionX() > self.slimeAnimNode:getPositionX() then
                self.slimeAnimNode:setScaleX(-1);
                pos = cc.pAdd(cc.p(item:getPosition()), cc.p(-50, 0));
            else
                self.slimeAnimNode:setScaleX(1);
                pos = cc.pAdd(cc.p(item:getPosition()), cc.p(50, 0));
            end

            local jumpTo = cc.JumpTo:create(1, pos, 30, 4);
            local callFunc = cc.CallFunc:create(function()
                self.slimeAnimNode:removeAllChildren();

                -- 播放捡取动画
                playEffect(self.slimeAnimNode, 1164, 0, 0);

                -- 待机动画
                local function delay()
                    item:setVisible(false);

                    local bonusNode = findChildByName(self.node, "layer/bonus"..index);
                    bonusNode:setColor(normalColor);
                    bonusNode:setVisible(true);
                    bonusNode:setCascadeColorEnabled(true);
                    local delay = cc.DelayTime:create(0.6);
                    local fadeOut = cc.FadeOut:create(0.4);
                    local fadeOutAction = cc.Sequence:create(delay, fadeOut);
                    local moveBy = cc.MoveBy:create(1, cc.p(0, 50));
                    local moveDone = cc.CallFunc:create(function()
                         bonusNode:setVisible(false);
                        showItem(index+1);
                    end);
                    bonusNode:runAction(cc.Sequence:create(cc.Spawn:create(fadeOutAction, moveBy), moveDone));

                    self.slimeAnimNode:removeAllChildren();
                    playEffect(self.slimeAnimNode, 1170, 0, 0);
                end
                performWithDelay(self.slimeAnimNode, delay, 1);
            end);

            -- 播放捡取动画
            self.slimeAnimNode:runAction(cc.Sequence:create(jumpTo, callFunc));
        end

        -- 手势指引
        local hand = item:getChildByName("hand");
        hand:setVisible(true);
        playClickEffect(hand);

        item:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");

                -- 拾取物品
                pickUpItem(index);
                item:removeAllChildren();
                item:setTouchEnabled(false);
            end
        end);
    end

    showItem(1);
end

-- 修理炼金炉
function UIWorkshopGuide:repairWorkshop(callback)
    -- 蹦向炼金炉
    local targetPos = cc.p(300, 400);

    local delay = cc.DelayTime:create(1);
    local callFunc1 = cc.CallFunc:create(function()
        self.slimeAnimNode:removeAllChildren();
        playEffect(self.slimeAnimNode, 1163, 0, 0);

        if targetPos.x > self.slimeAnimNode:getPositionX() then
            self.slimeAnimNode:setScaleX(-1);
        else
            self.slimeAnimNode:setScaleX(1);
        end
        AudioM.playFx("workshop_guide05");
    end);
    local jumpTo = cc.JumpTo:create(1, targetPos, 30, 4);
    local callFunc2 = cc.CallFunc:create(function()
        self.slimeAnimNode:removeAllChildren();

        -- 待机动画
        playEffect(self.slimeAnimNode, 1170, 0, 0);
        self.slimeAnimNode:setVisible(false);

        -- 播放修理动画
        local repairAnimNode = findChildByName(self.node, "layer/repair_anim");
        playEffect(repairAnimNode, 1166, -50, -50);

        local delay = cc.DelayTime:create(1.5);
        local repairFunc1 = cc.CallFunc:create(function()
            local furnace = findChildByName(self.node, "layer/furnace");
            furnace:setVisible(false);

            -- 炼金炉膨胀
            playEffect(repairAnimNode, 1168, -98, 55);
        end);
        local delay2 = cc.DelayTime:create(0.5);
        local repairFunc2 = cc.CallFunc:create(function()
            -- 爆炸特效
            playEffect(repairAnimNode, 1171, -80, 140);
        end);
        local delay3 = cc.DelayTime:create(1);
        local done = cc.CallFunc:create(function()
            self.slimeAnimNode:setVisible(true);
            if callback then
                callback();
            end
        end);

        self.slimeAnimNode:runAction(cc.Sequence:create(delay, repairFunc1, delay2, repairFunc2, delay3, done));
    end)

    self.slimeAnimNode:runAction(cc.Sequence:create(delay, callFunc1, jumpTo, callFunc2));
end

-- 打开真正的炼金主界面
function UIWorkshopGuide:startWorking()
    UIMgr.getCurrentScene():removeFormByName("UIWorkshopGuide");

    local uiForm = UINewWorkshop:create()
    UIMgr:getCurrentScene():addForm(uiForm);

end

